package com.jiuyun.Servlet;

import com.google.gson.Gson;
import com.jiuyun.dao.StudentDao;
import com.jiuyun.dao.impl.StudentDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/json")
public class JsonServlet extends HttpServlet {

    StudentDao dao = new StudentDaoImpl();
    Gson gson = new Gson();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String s = null;
        try {
            List list =  dao.getStu();
            s = gson.toJson(list);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        //如何让servlet返回json数据
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        //输出流
        PrintWriter out = response.getWriter();
        out.println(s);  //数据
        out.flush();
        out.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
